//
//  BkFaceDetailViewController.m
//  TuDianEducation
//
//  Created by lixinkeji on 2021/1/12.
//  Copyright © 2021 zhangbenchao. All rights reserved.
//


#import "BkFaceDetailViewController.h"
#import "BkFaceOptionViewController.h"
#import "BkJuBaoViewController.h"

#import "BkFaceDetailHeader.h"
#import "BkFaceDetailSelectView.h"
#import "BkCommendsTableViewCell.h"
#import "PopoverViewController.h"

@interface BkFaceDetailViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UIPopoverPresentationControllerDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic) NSInteger pageNum;

@property (nonatomic,strong) BkFaceDetailSelectView *selctionView;
@property (nonatomic,strong) BkFaceDetailHeader *headerView;

@property (nonatomic,strong) UITextField *commendTextFiled;
@property (nonatomic,strong) UIButton *sendBtn;
@property (nonatomic,strong) NSDictionary *dataDic;
///类型 0全部 1只看作者
@property (nonatomic,strong) NSString *type;
///sort 排序 0时间倒序 1时间正序 2点赞最多
@property (nonatomic,strong) NSString *sort;
///taid对方id (二级评论要传,传了是回复对方,)
@property (nonatomic,strong) NSString *taid;
///dcid一级评论id (传了是是二级评论 不传是一级评论)
@property (nonatomic,strong) NSString *dcid;

@end

@implementation BkFaceDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.automaticallyAdjustsScrollViewInsets = YES;
    _type = @"0";
    _sort = @"1";
    [self.view addSubview:self.tableView];
    self.view.backgroundColor = kWhiteColor;
    
    [self.view addSubview:self.sendBtn];
    [self.view addSubview:self.commendTextFiled];
    [self reqDongtaiDetai];
    self.title = @"动态详情";
    ///默认评论作品本身
    self.taid = @"";
    self.dcid = @"";
    
    
}
-(UITextField *)commendTextFiled{
    if (!_commendTextFiled) {
        _commendTextFiled = [TSWLTools allocTextFieldTextFont:TSScaleW(14) placeHolderFont:TSScaleW(14) text:nil placeText:@"请输入文字 评论动态" textColor:kMainTxtColor placeHolderTextColor:kGrayTxtColor frame:CGRectMake(TSScaleW(12), TSScreenHeight - Height_NavBar - TSScaleW(45),TSScaleW(291), TSScaleW(30))];
        _commendTextFiled.cornerRadius = _commendTextFiled.height/2.f;
        _commendTextFiled.leftViewMode = UITextFieldViewModeAlways;
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, TSScaleW(20), _commendTextFiled.height)];
        
        _commendTextFiled.leftView = view;
        _commendTextFiled.backgroundColor = kMainBgColor;
        _commendTextFiled.delegate = self;
    }
    return _commendTextFiled;
}

-(UIButton *)sendBtn{
    if (!_sendBtn) {
        _sendBtn = [TSWLTools allocButtonTitle:@"发送" font:systemFont(TSScaleW(13)) textColor:kWhiteColor image:nil frame:CGRectMake(TSScaleW(314), TSScreenHeight - Height_NavBar - TSScaleW(45), TSScaleW(50), TSScaleW(30)) sel:@selector(sendBtnAction:) taget:self];
        _sendBtn.backgroundColor = kGreenColor;
        [_sendBtn setCornerRadius:_sendBtn.height/2.f];
    }
    return _sendBtn;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self headerRefresh];
}
-(NSArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
-(BkFaceDetailSelectView *)selctionView{
    if (!_selctionView) {
        _selctionView = [[BkFaceDetailSelectView alloc]init];
        WS(weakSelf);
        _selctionView.typeBlock = ^(NSString * _Nonnull type) {
            weakSelf.type = type;
            [weakSelf.tableView.mj_header beginRefreshing];
        };
        _selctionView.timeShowBlock = ^(UIButton * _Nonnull sender) {
            [weakSelf sortAction:sender];
        };
    }
    return _selctionView;
}
-(void)sortAction:(UIButton *)sender
{
//排序 0时间倒序 1时间正序 2点赞最多
    NSMutableArray *nameArray = [NSMutableArray arrayWithArray:@[@"时间倒序",@"时间正序",@"点赞最多"]];
    
    
    PopoverViewController *vc =  [self getPopVCWithData:nameArray soureView:sender];
       vc.preferredContentSize = CGSizeMake(140, 132);
      [self presentViewController:vc animated:YES completion:nil];
    WS(weakSelf);
    NSArray *indexArray = @[@"0",@"1",@"2"];
       vc.popActionBlock = ^(NSInteger index) {
           weakSelf.sort = indexArray[index];
           [sender setTitle:nameArray[index] forState:(UIControlStateNormal)];
           [weakSelf.tableView.mj_header beginRefreshing];
       };
}
- (PopoverViewController *)getPopVCWithData:(NSArray *)array soureView:(UIView *)soureView{
    
    PopoverViewController *popContentVC = [PopoverViewController new];
    popContentVC.preferredContentSize = CGSizeMake(140, 132);
    popContentVC.modalPresentationStyle = UIModalPresentationPopover;
    popContentVC.dataArray= array.mutableCopy;
    UIPopoverPresentationController *popController = [popContentVC popoverPresentationController];
    popController.backgroundColor = [UIColor whiteColor];
    popController.delegate = self;
    popController.sourceView = soureView;
    popController.sourceRect = CGRectMake(20, 0, soureView.width , soureView.height);
    return popContentVC;
}
//popview 代理
- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller {
    return UIModalPresentationNone;
}
-(BkFaceDetailHeader *)headerView{
    if (!_headerView) {
        _headerView = [[BkFaceDetailHeader alloc]init];
        WS(weakSelf);
        _headerView.reloadFrameBlock = ^{
            weakSelf.tableView.tableHeaderView = weakSelf.headerView;
        };
        _headerView.dianzanBlock = ^(UIButton * _Nonnull sender) {
            [weakSelf reqdianzanWithdcid:@"" button:sender];
        };
    }
    return _headerView;
}
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, TSScreenWidth, TSScreenHeight - Height_NavBar - TSScaleW(50) ) style:(UITableViewStyleGrouped)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableHeaderView = self.headerView;
        if (@available(iOS 11.0, *))
        {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
        }
        else
        {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        WS(weakSelf);
        _tableView.mj_header = [CustomGifHeader headerWithRefreshingBlock:^{
                [weakSelf headerRefresh];
        }];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                [weakSelf footerRefresh];
        }];
    }
    return _tableView;
}


#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BkCommendsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BkCommendsTableViewCell"];
    if (!cell) {
        cell = [[BkCommendsTableViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"BkCommendsTableViewCell"];
  
    }
    WS(weakSelf);
    NSDictionary *dic = self.dataArray[indexPath.row];
    cell.moreBlock = ^{
        BkFaceOptionViewController *vc = [[BkFaceOptionViewController alloc]init];
        [weakSelf preasntVc:vc];
        vc.callBackBlcok = ^(NSInteger index) {
            //0举报用户1删除
            if (index == 1) {
                NSString * userid = dic[@"userid"];
                if ([userid isEqualToString:kToken]) {
                    [weakSelf  deletedynamiccommWithdcid:dic[@"dcid"]];
                }else{
                    [MBProgressHUD showError:@"你不能删除别人的评论哦"];
                }
                
            };
            if (index == 0) {
                BkJuBaoViewController *vc = [[BkJuBaoViewController alloc]init];
                [weakSelf preasntVc:vc];
                vc.callBackBlcok = ^(NSString * _Nonnull message) {
                    [weakSelf addreportscommWithtaid:dic[@"userid"] content:message];
                };
            };
        };
    };
    cell.likeBlock = ^(UIButton * _Nonnull sender) {
        [weakSelf reqdianzanWithdcid:dic[@"dcid"] button:sender];
    };
    cell.dataDic = dic;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.dataArray[indexPath.row];
    [self commendisDongTai:dic];
    
}


#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.dataArray[indexPath.row];
    NSString * f = dic[@"allHeight"];
    return f.floatValue;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [[UIView alloc]initWithFrame:CGRectZero];
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, TSScreenWidth, TSScaleW(50))];
    [view addSubview:self.selctionView];
    view.backgroundColor = kMainBgColor;
    return view;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return TSScaleW(50);
}

#pragma mark - 上拉、下拉

-(void)headerRefresh
{
    self.pageNum = 1;
    [self collectListReq];
}

-(void)footerRefresh
{
    [self collectListReq];
}
-(void)collectListReq
{
    NSDictionary *pamas = @{@"pageNo":[NSString stringWithFormat:@"%ld",self.pageNum],@"pageSize":[NSString stringWithFormat:@"%d",kPage_Size],@"did":_did,@"sort":_sort,@"type":_type};
   

    [NetWorkTools postConJSONWithUrl:@"getdynamiccommlist" parameters:pamas success:^(id responseObject) {
        NSString *result = responseObject[@"result"];
        NSString *resultNote = responseObject[@"resultNote"];
        NSArray *array = responseObject[@"dataList"];
        NSMutableArray *mArray = [NSMutableArray array];
        if (result.integerValue == 0) {
            for (int i = 0; i < array.count; i ++) {
                NSDictionary *d = array[i];
                NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                [dic addEntriesFromDictionary:d];
                [mArray addObject:dic];
                NSArray *array  = d[@"secondList"];
                CGFloat  height = array.count * TSScaleW(45) + TSScaleW(145);
                [dic setValue:[NSString stringWithFormat:@"%f",height] forKey:@"allHeight"];
                
            }
            [self handleListWithModel:mArray];
        }else{
             [MBProgressHUD showError:resultNote];
        }

    } fail:^(NSError *error) {

    }];
}

-(void)endRefrash

{
    if (self.tableView.mj_header.state == MJRefreshStateRefreshing) {
        [self.tableView.mj_header endRefreshing];
    }
    
    if (self.tableView.mj_footer.state == MJRefreshStateRefreshing) {
        [self.tableView.mj_footer endRefreshing];
    }
}
-(void)handleListWithModel:(NSArray *)result
{
    
    if (self.pageNum == 1) {
        [self.dataArray removeAllObjects];
    }
    
    if (result.count != kPage_Size) {
        self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
    }else{
        self.tableView.mj_footer.state = MJRefreshStateIdle;
    }
    
    [self.dataArray addObjectsFromArray:result];
   
  // [SSKJ_NoDataView showNoData:self.dataArray.count toView:self.tableView offY:TSScaleW(10) message:@"还没有数据哦~" imge:[UIImage imageNamed:@"nolikesimg"]];
    
    self.pageNum++;
    
    [self endRefrash];
    
    [self.tableView reloadData];
    
}
#pragma mark ----请求动态详情
-(void)reqDongtaiDetai
{
    NSDictionary *pamas = @{@"did":[NSString stringWithFormat:@"%@",self.did]};
   

    [NetWorkTools postConJSONWithUrl:@"getdynamicdetail" parameters:pamas success:^(id responseObject) {
        NSString *result = responseObject[@"result"];
        NSString *resultNote = responseObject[@"resultNote"];
        NSDictionary *dataobject = responseObject[@"dataobject"];
        if (result.integerValue == 0) {
           
            self.dataDic = dataobject;
        }else{
             [MBProgressHUD showError:resultNote];
        }

    } fail:^(NSError *error) {

    }];
}
-(void)setDataDic:(NSDictionary *)dataDic{
    _dataDic = dataDic;
    
    self.headerView.dataDic = _dataDic;
}
#pragma mark ---点赞/取消点赞
-(void)reqdianzanWithdcid:(NSString *)dcid button:(UIButton *)sender
{
    NSDictionary *pamas = @{@"did":[NSString stringWithFormat:@"%@",self.did],@"dcid":dcid};
   

    [NetWorkTools postConJSONWithUrl:@"dynamiczan" parameters:pamas success:^(id responseObject) {
        NSString *result = responseObject[@"result"];
        NSString *resultNote = responseObject[@"resultNote"];
       
        if (result.integerValue == 0) {
            //sender.selected = !sender.selected;
            if (dcid.length) {
                [self headerRefresh];
            }else{
                [self reqDongtaiDetai];
            }
            
        }else{
            
        }
        [MBProgressHUD showError:resultNote];
    } fail:^(NSError *error) {

    }];
}
#pragma mark ---发布评论
-(void)reqadddynamiccommWithdcid:(NSString *)dcid taid:(NSString *)taid commends:(NSString *)commends
{
    NSDictionary *pamas = @{@"did":[NSString stringWithFormat:@"%@",self.did],@"dcid":dcid,@"taid":taid,@"content":commends};
   

    [NetWorkTools postConJSONWithUrl:@"adddynamiccomm" parameters:pamas success:^(id responseObject) {
        NSString *result = responseObject[@"result"];
        NSString *resultNote = responseObject[@"resultNote"];
       
        if (result.integerValue == 0) {
           
            [self.tableView.mj_header beginRefreshing];
            [self commendisDongTai:@{}];
            [self reqDongtaiDetai];
        }else{
            
        }
        [MBProgressHUD showError:resultNote];
    } fail:^(NSError *error) {

    }];
}
-(void)sendBtnAction:(UIButton *)sender
{
    if (!_commendTextFiled.text.length) {
        [MBProgressHUD showError:@"请输入评论"];
        return;
    }
   
    [self reqadddynamiccommWithdcid:_dcid taid:_taid commends:_commendTextFiled.text];
}

-(void)commendisDongTai:(NSDictionary *)dic
{
    if ([dic isEqual:@{}]) {
        _dcid = @"";
        _taid = @"";
        _commendTextFiled.text = @"";
        _commendTextFiled.placeholder = @"请输入文字评论动态";
    }else{
        _dcid = dic[@"dcid"];
        _taid = dic[@"userid"];
        _commendTextFiled.text = @"";
        NSString *message = [NSString stringWithFormat:@"请输入文字评论%@",dic[@"usernickname"]];
        _commendTextFiled.placeholder = message;
    }
}
#pragma mark ---删除评论
-(void)deletedynamiccommWithdcid:(NSString *)dcid
{
    NSDictionary *pamas = @{@"did":[NSString stringWithFormat:@"%@",self.did],@"dcid":dcid};
   

    [NetWorkTools postConJSONWithUrl:@"deletedynamiccomm" parameters:pamas success:^(id responseObject) {
        NSString *result = responseObject[@"result"];
        NSString *resultNote = responseObject[@"resultNote"];
       
        if (result.integerValue == 0) {
            [self.tableView.mj_header beginRefreshing];
            [self reqDongtaiDetai];
        }else{
            
        }
        [MBProgressHUD showError:resultNote];
    } fail:^(NSError *error) {

    }];
}
#pragma mark ---举报用户

-(void)addreportscommWithtaid:(NSString *)taid content:(NSString *)content
{
    NSDictionary *pamas = @{@"taid":[NSString stringWithFormat:@"%@",taid],@"content":content};
   

    [NetWorkTools postConJSONWithUrl:@"addreports" parameters:pamas success:^(id responseObject) {
        NSString *result = responseObject[@"result"];
        NSString *resultNote = responseObject[@"resultNote"];
       
        if (result.integerValue == 0) {
            //[self.tableView.mj_header beginRefreshing];
        }else{
            
        }
        [MBProgressHUD showError:resultNote];
    } fail:^(NSError *error) {

    }];
}
@end
